import merge from 'lodash.merge';
import type {
  CrudPageConfig,
} from '../interface';
import type { ProColumns } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-components';
import { getDefaultFormLayout } from '../utils/transData';


export function getDefaultCurdPageConfig() {
  const config: Partial<CrudPageConfig> = {
    primaryKey: 'id',
    showFilter: true,
    showPagination: true,
    columns: [],
    filterColumns: [],
    addFormColumns: [],
    editFormColumns: [],
    loadDetailsForModify: false,
    detailFormLayout: getDefaultFormLayout(),
    PageContainer,
    showOpColumn: true,
    columnPublicProps: {
      width: 190,
    },
    paginationPublicProps: {
      pageSize: 10,
    },
    tablePublicProps: {
      headerTitle: '数据列表',
    },
    showConciseSearch: false,
    conciseSearchProps: {
      placeholder: '请输入关键字',
    },
    conciseSearchFieldKey: 'keyword',
  };
  return config;
}

export function calcCurdPageConfig(sourceConfig: Partial<CrudPageConfig>) {
  const base = getDefaultCurdPageConfig();
  const dist: CrudPageConfig = merge({}, base, sourceConfig) as unknown as CrudPageConfig;
  const { filterKeys = [], columnsKeys = [], detailFormKeys = [], columnsMap } = dist;
  const columns: ProColumns[] = [];
  const filterColumns: ProColumns[] = [];
  const addFormColumns: ProColumns[] = [];
  const keys = Object.keys(columnsMap);

  keys.forEach((key) => {
    columnsMap[key].hideInTable = true;
    columnsMap[key].hideInSearch = true;
    if (filterKeys.includes(key)) {
      columnsMap[key].hideInSearch = false;
    }
    if (columnsKeys.includes(key)) {
      columnsMap[key].hideInTable = false;
    }
    if (detailFormKeys.includes(key)) {
      addFormColumns.push(columnsMap[key] as ProColumns);
    }
  });
  columnsKeys.forEach((key) => {
    if (columnsMap[key]) {
      columns.push(columnsMap[key] as ProColumns);
    }
  });
  filterKeys.forEach((key) => {
    if (columnsMap[key] && !columnsKeys.includes(key)) {
      columns.push(columnsMap[key] as ProColumns);
    }
  });
  dist.filterColumns = filterColumns;
  dist.columns = columns;
  dist.addFormColumns = addFormColumns;
  if (dist.editFormColumns.length === 0) {
    dist.editFormColumns = addFormColumns;
  }
  console.info(' calcCurdPageConfig ~ dist', dist);
  return dist;
}
